<template>
  <div class="user-detail">
    <h2 class="page-title">个人资料</h2>

    <!-- 用户信息编辑卡片 -->
    <div class="user-profile-card">
      <!-- 卡片上半部分：头像和基本信息 -->
      <div class="card-top">
        <!-- 左侧头像区 -->
        <div class="avatar-section">
          <a-avatar :size="120" :src="userInfo.userAvatar" class="avatar">
            <template #icon><UserOutlined /></template>
          </a-avatar>
          <div class="avatar-upload">
            <a-upload
              name="file"
              :show-upload-list="false"
              :before-upload="beforeUpload"
              @change="handleAvatarChange"
              accept="image/*"
              :customRequest="customRequest"
            >
              <a-button class="upload-btn">头像更换</a-button>
            </a-upload>
          </div>
        </div>

        <!-- 右侧基本信息区 -->
        <div class="basic-info-section">
          <div class="info-item">
            <span class="info-label">用户名：</span>
            <span class="info-value">
              <a-input
                v-model:value="userInfo.userName"
                placeholder="请输入用户名"
                :disabled="!editing.userName"
                :bordered="editing.userName"
                class="custom-input"
              />
              <a-button
                v-if="!editing.userName"
                type="link"
                class="edit-btn"
                @click="startEditing('userName')"
              >
                <edit-outlined />
              </a-button>
            </span>
            <div class="edit-actions" v-if="editing.userName">
              <a-button type="primary" size="small" @click="saveUserName"
                >保存</a-button
              >
              <a-button size="small" @click="cancelEditing('userName')"
                >取消</a-button
              >
            </div>
          </div>

          <div class="info-item">
            <span class="info-label">用户角色：</span>
            <span class="info-value">{{ userRoleText }}</span>
          </div>
        </div>
      </div>

      <!-- 卡片下半部分：个人简介 -->
      <div class="card-bottom">
        <div class="profile-section">
          <div class="profile-header">
            <span>个人简介</span>
            <a-button
              v-if="!editing.userProfile"
              type="link"
              class="edit-btn"
              @click="startEditing('userProfile')"
            >
              <edit-outlined />
            </a-button>
          </div>
          <a-textarea
            v-model:value="userInfo.userProfile"
            :rows="4"
            placeholder="这个人很懒，什么都没有留下..."
            :disabled="!editing.userProfile"
            :bordered="editing.userProfile"
            class="profile-textarea"
          />
          <div class="edit-actions" v-if="editing.userProfile">
            <a-button type="primary" size="small" @click="saveProfile"
              >保存</a-button
            >
            <a-button size="small" @click="cancelEditing('userProfile')"
              >取消</a-button
            >
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from "vue";
import { message } from "ant-design-vue";
import { UserOutlined, EditOutlined } from "@ant-design/icons-vue";
import {
  getLoginUserUsingGet,
  updateUserUsingPost,
} from "@/api/userController";
import { uploadFileUsingPost } from "@/api/cosController";
import { useLoginUserStore } from "@/store/userStore";

// 用户信息
const userInfo = reactive({
  id: "",
  userAccount: "", // 添加userAccount字段
  userName: "",
  userAvatar: "",
  userProfile: "",
  userRole: "",
  createTime: "",
});

// 记录原始信息（用于取消编辑）
const originalInfo = reactive({
  userName: "",
  userProfile: "",
});

// 编辑状态
const editing = reactive({
  userName: false,
  userProfile: false,
});

// 将userRole转换为用户角色显示文本
const userRoleText = computed(() => {
  switch (userInfo.userRole) {
    case "admin":
      return "管理员";
    case "user":
      return "普通用户";
    default:
      return "普通用户";
  }
});

// 引入用户存储
const userStore = useLoginUserStore();

// 获取用户信息
const fetchUserInfo = async () => {
  try {
    const res = await getLoginUserUsingGet();
    // 使用类型断言
    const apiRes = res as any;
    if (apiRes.data && apiRes.data.code === 0 && apiRes.data.data) {
      const userData = apiRes.data.data;
      Object.assign(userInfo, userData);
      // 保存原始信息
      originalInfo.userName = userData.userName || "";
      originalInfo.userProfile = userData.userProfile || "";
    } else {
      message.error((apiRes.data && apiRes.data.message) || "获取用户信息失败");
    }
  } catch (error: any) {
    console.error("获取用户信息失败:", error);
    message.error("获取用户信息失败");
  }
};

// 开始编辑
const startEditing = (field: "userName" | "userProfile") => {
  editing[field] = true;
};

// 取消编辑
const cancelEditing = (field: "userName" | "userProfile") => {
  editing[field] = false;
  userInfo[field] = originalInfo[field];
};

// 保存用户名
const saveUserName = async () => {
  if (!userInfo.userName) {
    message.error("用户名不能为空");
    return;
  }

  try {
    const res = await updateUserUsingPost({
      id: Number(userInfo.id),
      userName: userInfo.userName,
    });
    // 使用类型断言
    const apiRes = res as any;

    if (apiRes.data && apiRes.data.code === 0) {
      // 更新本地状态
      originalInfo.userName = userInfo.userName;

      // 更新用户存储中的用户名
      await userStore.updateUserInfo({ userName: userInfo.userName });

      message.success("用户名修改成功");
      editing.userName = false;
    } else {
      message.error((apiRes.data && apiRes.data.message) || "用户名修改失败");
    }
  } catch (error: any) {
    console.error("用户名修改失败:", error);
    message.error("用户名修改失败");
  }
};

// 保存个人简介
const saveProfile = async () => {
  try {
    const res = await updateUserUsingPost({
      id: Number(userInfo.id),
      userProfile: userInfo.userProfile,
    });
    // 使用类型断言
    const apiRes = res as any;

    if (apiRes.data && apiRes.data.code === 0) {
      // 更新本地状态
      originalInfo.userProfile = userInfo.userProfile;

      // 更新用户存储中的个人简介
      await userStore.updateUserInfo({ userProfile: userInfo.userProfile });

      message.success("个人简介修改成功");
      editing.userProfile = false;
    } else {
      message.error((apiRes.data && apiRes.data.message) || "个人简介修改失败");
    }
  } catch (error: any) {
    console.error("个人简介修改失败:", error);
    message.error("个人简介修改失败");
  }
};

// 头像上传前检查
const beforeUpload = (file: File) => {
  const isJpgOrPng = file.type === "image/jpeg" || file.type === "image/png";
  if (!isJpgOrPng) {
    message.error("只能上传JPG或PNG格式的图片!");
  }
  const isLt2M = file.size / 1024 / 1024 < 2;
  if (!isLt2M) {
    message.error("图片必须小于2MB!");
  }
  return isJpgOrPng && isLt2M;
};

// 处理头像上传
const handleAvatarChange = async (info: any) => {
  const { status, originFileObj } = info.file;

  if (status === "uploading") {
    message.loading({ content: "头像上传中...", key: "avatarUpload" });
    return;
  }

  if (status !== "done") {
    return;
  }

  // 隐藏上传中的消息
  message.destroy("avatarUpload");

  if (!originFileObj) {
    message.error("未找到上传文件");
    return;
  }

  try {
    // 显示上传中消息
    message.loading({ content: "正在处理...", key: "avatarUpload" });

    // 先上传到服务器
    const uploadRes = await uploadFileUsingPost({}, originFileObj);
    // 使用类型断言
    const apiUploadRes = uploadRes as any;

    console.log("文件上传响应:", apiUploadRes);

    if (apiUploadRes.data && apiUploadRes.data.code === 0) {
      const avatarUrl = apiUploadRes.data.data;

      console.log("上传成功，获取的头像URL:", avatarUrl);

      // 更新用户信息
      const updateRes = await updateUserUsingPost({
        id: Number(userInfo.id),
        userAvatar: avatarUrl,
      });
      // 使用类型断言
      const apiUpdateRes = updateRes as any;

      console.log("更新用户信息响应:", apiUpdateRes);

      if (apiUpdateRes.data && apiUpdateRes.data.code === 0) {
        // 更新本地状态
        userInfo.userAvatar = avatarUrl;

        // 更新用户存储中的头像信息
        await userStore.updateUserInfo({ userAvatar: avatarUrl });

        message.success({ content: "头像更新成功", key: "avatarUpload" });
      } else {
        message.error({
          content:
            (apiUpdateRes.data && apiUpdateRes.data.message) || "头像更新失败",
          key: "avatarUpload",
        });
      }
    } else {
      message.error({
        content:
          (apiUploadRes.data && apiUploadRes.data.message) || "头像上传失败",
        key: "avatarUpload",
      });
    }
  } catch (error: any) {
    console.error("头像上传失败:", error);
    message.error({ content: "头像上传失败，请重试", key: "avatarUpload" });
  }
};

// 自定义上传请求（阻止默认上传）
const customRequest = ({ file, onSuccess }: any) => {
  // 模拟成功状态，让 handleAvatarChange 接收到文件
  setTimeout(() => {
    onSuccess();
  }, 0);
};

onMounted(() => {
  fetchUserInfo();
});
</script>

<style scoped>
.user-detail {
  width: 100%;
  padding: 20px;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.page-title {
  font-size: 22px;
  color: #333;
  margin-bottom: 20px;
  border-left: 4px solid #8c4b3c;
  padding-left: 10px;
}

.user-profile-card {
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  margin-bottom: 20px;
  overflow: hidden;
}

/* 卡片上半部分样式 */
.card-top {
  display: flex;
  padding: 24px;
  border-bottom: 1px solid #e8e8e8;
}

/* 左侧头像区样式 */
.avatar-section {
  flex: 0 0 150px;
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 16px;
}

.avatar {
  border: 4px solid #f0f0f0;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.upload-btn {
  background: #eea75f;
  border: none;
  color: white;
  transition: all 0.3s ease;
}

.upload-btn:hover {
  background: #d9964e;
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(140, 75, 60, 0.3);
}

/* 右侧基本信息区样式 */
.basic-info-section {
  flex: 1;
  padding-left: 30px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  gap: 16px;
}

.info-item {
  display: flex;
  align-items: center;
  position: relative;
}

.info-label {
  width: 80px;
  color: #666;
  font-weight: 500;
}

.info-value {
  flex: 1;
  font-size: 16px;
  color: #333;
  display: flex;
  align-items: center;
}

.custom-input {
  border: none;
  background-color: transparent;
  padding: 0;
}

.custom-input:disabled {
  color: #333;
}

.edit-btn {
  color: #8c4b3c;
  padding: 0 8px;
}

.edit-actions {
  display: flex;
  gap: 8px;
  margin-left: 8px;
}

/* 卡片下半部分样式 */
.card-bottom {
  padding: 24px;
}

.profile-section {
  width: 100%;
}

.profile-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  font-size: 16px;
  font-weight: 500;
  color: #666;
}

.profile-textarea {
  width: 100%;
  resize: none;
  background-color: #f9f9f9;
  border: none;
  border-radius: 4px;
}

.profile-textarea:disabled {
  color: #333;
  background-color: #f9f9f9;
}

/* 响应式调整 */
@media screen and (max-width: 768px) {
  .card-top {
    flex-direction: column;
    align-items: center;
    gap: 20px;
  }

  .avatar-section {
    margin-bottom: 20px;
  }

  .basic-info-section {
    padding-left: 0;
    width: 100%;
  }

  .info-item {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
  }

  .info-label {
    width: 100%;
  }
}
</style>
